package com.charles.seckillManagement.service.impl;


import com.charles.seckillComponentCommon.constants.CacheConstants;
import com.charles.seckillComponentCommon.exceptions.ServiceException;
import com.charles.seckillComponentCommon.utils.StringUtils;
import com.charles.seckillComponentRedis.service.RedisService;
import com.charles.seckillData.domain.SysGood;
import com.charles.seckillManagement.service.SysGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Service
public class SysGoodServiceImpl implements SysGoodService {

    @Autowired
    private RedisService redisService;

    // 将抢购开始时间小于 24小时的产品放入缓存中。
    @Override
    public void checkGoodIsSeckill(SysGood good) {
        String cacheKey = CacheConstants.GOOD_ID + good.getGood_id();
        if (good.getIs_seckill().equals("1")) {
            Date startDate = good.getStart_time();
            LocalDateTime startDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

            LocalDateTime now = LocalDateTime.now();

            Duration durationUntilStart = Duration.between(now, startDateTime);
            boolean isWithin24Hours = durationUntilStart.abs().toHours() <= 24;

            if (!now.isAfter(startDateTime) && isWithin24Hours) {
                redisService.setCacheObject(cacheKey, good);
            }
        } else {
            if (redisService.getCacheObject(cacheKey) != null) {
                redisService.deleteObject(cacheKey);
            }
        }
    }

    @Override
    public void verifyGoodForm(SysGood good) {
        if (StringUtils.isEmpty(good.getGood_img())
                || StringUtils.isEmpty(good.getGood_title())
                || good.getPrice() == null
                || good.getTotal() == null) {
            throw new ServiceException("请完善表单信息");
        }

        if (good.getIs_seckill().equals("1") 
                && (good.getSeckill_price() == null 
                || good.getStart_time() == null 
                || good.getEnd_time() == null)) {
            throw new ServiceException("请完善表单信息");
        }
        
    }
}
